from constants import *
import pygame, sys
from pygame.locals import *
# 蛇组件
class SNACK :
    Lenth = 4
    Unit = 10
    right = 0
    up = 1
    left = 2
    down = 3
    def __init__(self, xx, yy) :
        self.head = [xx, yy]
        self.body = [[xx - i * SNACK.Unit, yy] for i in range(1, 4)]
        self.originDirection = SNACK.right
        self.nowDirection = SNACK.right
    # 打印
    def printSnack(self, screen) :
        def snackRect(k) :
            return [k[0], k[1], SNACK.Unit, SNACK.Unit]
        pygame.draw.rect(screen, snackHeadColor, snackRect(self.head))
        for i in self.body :
            pygame.draw.rect(screen, snackBodyColor, snackRect(i))
    # 键盘事件检测
    def checkKeydown(self, event) :
        return event.type == KEYDOWN
    # 蛇的方向更新
    def updateDirection(self, event) :
        targetDirection = self.nowDirection
        if event.key == K_RIGHT or event.key == K_d :
            targetDirection = SNACK.right
        if event.key == K_LEFT or event.key == K_a :
            targetDirection = SNACK.left
        if event.key == K_UP or event.key == K_w :
            targetDirection = SNACK.up
        if event.key == K_DOWN or event.key == K_s :
            targetDirection = SNACK.down
        
        diff = abs(targetDirection - self.nowDirection)
        if diff == 1 or diff == 3 :
            self.originDirection = self.nowDirection
            self.nowDirection = targetDirection
    # 位置更新
    def updatePosition(self, flag) :
        move = [[SNACK.Unit, 0], [0, -SNACK.Unit], [-SNACK.Unit, 0], [0, SNACK.Unit]]
        self.body.insert(0, self.head)
        add = lambda x, y : x + y
        self.head = list(map(add, self.head, move[self.nowDirection]))
        if flag : self.body.pop()
    # 碰撞检测
    def checkCollision(self, mp) :
        x = self.head[0]
        y = self.head[1]
        if x < mp.Left or x >= mp.Right : return True
        if y < mp.Top or y >= mp.Bottom : return True
        try :
            self.body.index(self.head)
            exist = True
        except :
            exist = False
        return exist